#!/usr/bin/env python
# coding:utf-8


from PyQt4 import QtGui
from sql_rice.gui.action_area import ActionArea


class FormWindow(QtGui.QMainWindow):
    """Display one register in a Form Layout window"""

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        central = QtGui.QWidget(self)
        self.layout = QtGui.QVBoxLayout(central)
        self.setCentralWidget(central)
        self.widgets = {}
        self.actions = ActionArea(self)
        self.addToolBar(self.actions)

    def add_widget(self, widget):
        """add_widget(widget:Widget)->None"""
        self.widgets[widget.name] = widget
        self.layout.addWidget(widget)
    
    def update(self, values):
        """update(values:dict)->None"""
        for name, widget in list(self.widgets.items()):
            try:
                widget.value = values[name]
            except KeyError:
                widget.value = ''

    def valide(self):
        """valide()->dict"""
        status = {}
        for name, wgt in list(self.widgets.items()):
            status[name] = wgt.valide()
        return status


class GridWindow(FormWindow):
    """Display multiple registers in a grid"""

    def __init__(self):
        FormWindow.__init__(self)
        self.table = QtGui.QTableView(self)
        self.table.setSelectionBehavior(1)
        self.layout.addWidget(self.table)
        self.model = QtGui.QStandardItemModel(self)
        self.selection_model = None
        
    def fill_grid(self, rows):
        """fill_grid(rows:dict)->None"""
        keys = list(rows[0].keys())
        self.model.setHorizontalHeaderLabels(keys)
        for item in rows:
            self.model.appendRow([QtGui.QStandardItem(item[name])\
                for name in keys])
        self.table.setModel(self.model)
        self.selection_model = QtGui.QItemSelectionModel(self.model)
        self.table.setSelectionModel(self.selectionModel)
        self.selection_model.selectionChanged.connect(self.update_register)

    def update_register(self, selected, deselected):
        """selection_changed(selected, deselected)->None"""
        row = self.selectionModel.currentIndex().row()
        columns = self.model.columnCount()
        name = lambda idx:str(self.model.horizontalHeaderItem(idx).text())
        value = lambda idx: str(self.model.item(row, idx).text())
        values = dict((name(i), value(i)) for i in range(columns))
        self.update(values)
        self.actions.register = values
